package com.xiaoshi.config;

import com.xiaoshi.oauth.impl.UserDetailLoginServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Order(2)
@EnableWebSecurity  //开启了和Web相关的安全配置。
public class ResSecurityConfigure extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailLoginServiceImpl userDetailService;


//    /**
//     * 密码模式
//     *
//     * @return
//     */
//    @Autowired
//    private PasswordEncoder passwordEncoder;



    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }


    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }





    @Override
    protected void configure(HttpSecurity http) throws Exception {


        http.requestMatchers()
                .antMatchers("/oauth/**")  //安全配置类只对/oauth/开头的请求有效。
                .and()
                .authorizeRequests()
                .and()
                .authorizeRequests()
                .antMatchers("/oauth/**").authenticated()
                .and()
                .httpBasic()
                .and()
                .csrf().disable();
    }


//    /**
//     * 自定义验证逻辑
//     * @param auth
//     * @throws Exception
//     */
//    @Override
//    protected void configure(AuthenticationManagerBuilder auth){
//        auth.authenticationProvider(provider);
//    }


    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {


        auth.userDetailsService(userDetailService).passwordEncoder(passwordEncoder());
    }


    /**
     * 放行 不走授权过滤链
     *
     * @param web
     * @throws Exception
     */
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers(HttpMethod.OPTIONS, "/**");
        web.ignoring().antMatchers("/phoneVerificationCode");
        web.ignoring().antMatchers("/forms/sys-forms/**");
        web.ignoring().antMatchers("/v2/api-docs");
        //TODO 这里是为了swage2 接口文档开放的，正式版本需要注释掉
      //  web.ignoring().antMatchers("/**");

    }

}